package net.mbl.ide.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 网络工具类
 * 
 * @author mbl
 * 
 */
public class NetUtils {
	public static void main(String[] args) {
		GetOpenedPort();
	}

	/**
	 * 获取可用端口
	 * 
	 * @return 可用端口号
	 */
	public static int GetOpenedPort() {
		try {
			ServerSocket serverSocket = new ServerSocket(0);
			serverSocket.close();
			System.out.println(serverSocket.getLocalPort());
			return serverSocket.getLocalPort();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}

	public static String getMacStr(byte[] mac) {
		if (mac == null)
			return null;
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < mac.length; i++) {
			sb.append(String.format("%02X%s", mac[i],
					(i < mac.length - 1) ? "-" : ""));
		}
		return sb.toString().toUpperCase();
	}
	public static String getMacNumberStr(byte[] mac) {
		if (mac == null)
			return null;
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < mac.length; i++) {
			sb.append(String.format("%02X", mac[i]));
		}
		return sb.toString().toUpperCase();
	}
	public static String getIpStr(byte[] ip) {
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < ip.length; i++) {
			if (i != 0) {
				sb.append(".");
			}
			// 字节转换为整数
			int temp = ip[i] & 0xff;
			String str = Integer.toString(temp);
			sb.append(str);
		}
		return sb.toString();
	}

	public static byte[] parseIp(String value) {
		// TODO Auto-generated method stub
		String[] tmp = value.split("\\.");
		byte[] ip = new byte[4];
		for (int i = 0; i < tmp.length; i++) {
			ip[i] = (byte) (Integer.parseInt(tmp[i]) & 0xff);
		}
		return ip;
	}

	public static List<byte[]> getMacList() {
		List<byte[]> list = new ArrayList<byte[]>();
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface
					.getNetworkInterfaces();
			while (nets.hasMoreElements()) {
				NetworkInterface ni = nets.nextElement();
				byte[] mac = ni.getHardwareAddress();
				if (mac != null && mac.length == 6)
					list.add(mac);
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	public static List<String> getMacStrList() {
		List<String> list = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface
					.getNetworkInterfaces();
			while (nets.hasMoreElements()) {
				NetworkInterface ni = nets.nextElement();
				byte[] mac = ni.getHardwareAddress();
				if (mac != null && mac.length == 6)
					list.add(NetUtils.getMacStr(mac));
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	public static List<String> getMacNumberStrList() {
		List<String> list = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface
					.getNetworkInterfaces();
			while (nets.hasMoreElements()) {
				NetworkInterface ni = nets.nextElement();
				byte[] mac = ni.getHardwareAddress();
				if (mac != null && mac.length == 6)
					list.add(NetUtils.getMacNumberStr(mac));
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * Returns the MAC address of the computer.
	 * 
	 * @return the MAC address
	 */
	public static List<String> getMacListByProcess() {

		String mac = null;
		List<String> list = new ArrayList<String>();
		String os = System.getProperty("os.name");
		if (os.startsWith("Windows")) {
			BufferedReader bufferedReader = null;
			Process process = null;
			try {
				process = Runtime.getRuntime().exec("ipconfig /all");
				bufferedReader = new BufferedReader(new InputStreamReader(
						process.getInputStream()));
				String line = null;
				int index = -1;
				while ((line = bufferedReader.readLine()) != null) {
					index = line.toLowerCase().indexOf("物理地址");
					if (index == -1) {
						index = line.toLowerCase().indexOf("physical address");
					}
					if (index >= 0) {
						index = line.indexOf(":");
						if (index >= 0) {
							mac = line.substring(index + 1).trim();
							if (mac.split("-").length == 6) {
								list.add(mac);
							}
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (bufferedReader != null) {
						bufferedReader.close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				bufferedReader = null;
				process = null;
			}
		} else if (os.startsWith("Linux")) {
			String command = "/bin/sh -c ifconfig -a";
			Process p;
			try {
				p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("HWaddr") > 0) {
						int index = line.indexOf("HWaddr") + "HWaddr".length();
						String address = line.substring(index);
						list.add(address);
					}
				}
				br.close();
			} catch (IOException e) {
			}
		}
		return list;
	}
	
	public static InetAddress getINetAddress(String ipStr){
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface
					.getNetworkInterfaces();
			while (nets.hasMoreElements()) {
				NetworkInterface ni = nets.nextElement();
				String name = ni.getName();
				Enumeration<InetAddress> addrs = ni.getInetAddresses();
				while(addrs.hasMoreElements()){
					InetAddress addr = addrs.nextElement();
					String str  =addr.getHostAddress();
					if(ipStr.equals(str)){
						return addr;
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
